<template>
  <ElPopover v-model="showPopover" trigger="hover" popper-class="header-popover" class="menu-link">
    <template #reference>
      <span>
        <img ref="avatar" class="top-bar__img" alt="头像" :src="avatarUrl" />
        <span :class="['right-tab-menu']">{{ sysUser.name }}</span>
      </span>
    </template>
    <template #default>
      <div class="aside-item dropdown-menu-item">
        <p><i class="app-icon-common el-icon-office-building"></i> {{ sysUser.deptName }}</p>
      </div>
      <div class="aside-item dropdown-menu-item">
        <p><i class="app-icon-common el-icon-user"></i> {{ sysUser.name }}</p>
      </div>
      <div class="dropdown-menu-item" style="border-top: 1px solid #ddd" @click="onItemClick($event, '/info/index')">
        <i class="app-icon-common el-icon-postcard"></i>
        个人信息
      </div>
      <div class="dropdown-menu-item" @click="loginOut">
        <i class="app-icon-common el-icon-switch-button" style="color: red"></i> 退出
      </div>
    </template>
  </ElPopover>
</template>

<script>
  import { mapActions, mapState } from 'vuex'
  import { loginPath } from '@/config'
  import { getDataURL } from '@/util'

  export default {
    name: 'TopAvatar',
    data() {
      return {
        avatarUrl: require('@/assets/images/avatar.png'),
        showPopover: false
      }
    },
    computed: {
      ...mapState('user', ['sysUser'])
    },
    watch: {
      sysUser: {
        immediate: true,
        async handler(newVal) {
          if (newVal.avatar) {
            this.avatarUrl = (await getDataURL(newVal.avatar)) || this.avatarUrl
          }
        }
      }
    },
    methods: {
      ...mapActions('user', ['handleLogout']),
      onItemClick(event, path) {
        this.$router.push(path)
        this.showPopover = false
      },
      async loginOut() {
        this.showPopover = false
        try {
          await this.$confirm('确认退出吗？', '系统提示', {
            type: 'warning',
            beforeClose: async (action, instance, done) => {
              if (action === 'confirm') {
                try {
                  instance.confirmButtonLoading = true
                  instance.confirmButtonText = '正在退出...'
                  this.$bus('loginOut')
                  await this.handleLogout()
                  await this.$router.push(`/${loginPath}`)
                } catch (e) {
                  console.error(e)
                }
                done()
              } else {
                done()
              }
            }
          })
        } catch (_) {}
      }
    }
  }
</script>

<style lang="scss">
  .top-bar__img {
    box-sizing: border-box;
    width: 30px;
    height: 30px;
    margin-right: 4px;
    padding: 2px;
    vertical-align: middle;
    border: 1px solid #eee;
    border-radius: 100%;
  }
</style>
